package com.haha.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.haha.common.constant.ProductConstant;
import com.haha.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.haha.gulimall.product.dao.AttrGroupDao;
import com.haha.gulimall.product.dao.CategoryDao;
import com.haha.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.haha.gulimall.product.entity.AttrGroupEntity;
import com.haha.gulimall.product.entity.CategoryEntity;
import com.haha.gulimall.product.service.CategoryService;
import com.haha.gulimall.product.vo.AttrResponseVo;
import com.haha.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.common.utils.PageUtils;
import com.haha.common.utils.Query;

import com.haha.gulimall.product.dao.AttrDao;
import com.haha.gulimall.product.entity.AttrEntity;
import com.haha.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
       AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        System.out.println("检查保存后会返回id吗"+attrEntity);
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils getBaseAttrList(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> qw = new QueryWrapper<>();
        qw.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0){
            qw.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            qw.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),qw);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> attrResponseVos = records.stream().map(AttrEntity -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(AttrEntity, attrResponseVo);
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", AttrEntity.getAttrId()));

             if (attrAttrgroupRelationEntity != null ) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrId());
                if(attrGroupEntity!=null) attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            CategoryEntity categoryEntity = categoryDao.selectById(AttrEntity.getCatelogId());
            if(categoryEntity!=null){
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrResponseVos);
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        AttrEntity AttrEntity = getBaseMapper().selectById(attrId);
        BeanUtils.copyProperties(AttrEntity, attrResponseVo);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", AttrEntity.getAttrId()));
        if (attrAttrgroupRelationEntity != null ) {
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrId());
            attrResponseVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            if(attrGroupEntity!=null){
                attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        Long[] categroyPath = categoryService.getCategroyPath(AttrEntity.getCatelogId());
        attrResponseVo.setCatelogPath(categroyPath);
        CategoryEntity categoryEntity = categoryDao.selectById(AttrEntity.getCatelogId());
        if(categoryEntity!=null) attrResponseVo.setCatelogName(categoryEntity.getName());
        return attrResponseVo;

    }

    @Override
    public void updateAttr(AttrResponseVo attrResponseVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrResponseVo,attrEntity);
        this.updateById(attrEntity);

        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attrEntity.getAttrId());
        relationEntity.setAttrGroupId(attrResponseVo.getAttrGroupId());

       Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrResponseVo.getAttrId()));
        if(count>0){
            attrAttrgroupRelationDao.update(relationEntity,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrResponseVo.getAttrId()));
        }
        else {
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    /**
     * 获取这个分组所相关联的属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attr_group_id = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = attr_group_id.stream().map(obj -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        if(attrIds==null || attrIds.size()==0) return null;
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        return  attrEntities;
    }

    /**
     * * 获取分组还没有关联的属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //这个分组的分类
        AttrGroupEntity attr_group_id = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrgroupId));
        //查询这个分类的其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attr_group_id.getCatelogId()));
        //这些其他分组所使用的属性
        List<Long> otherGroupIds = attrGroupEntities.stream().map(obj -> {
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", otherGroupIds));
        List<Long> otherUsedAttrIds = attrAttrgroupRelationEntities.stream().map(obj -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        //在这个分类中的所有属性id把用过的属性id排除掉
        QueryWrapper<AttrEntity> qw = new QueryWrapper<AttrEntity>().eq("catelog_id", attr_group_id.getCatelogId()).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(otherUsedAttrIds!=null && otherUsedAttrIds.size()!=0){
           qw.notIn("attr_id", otherUsedAttrIds);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            qw.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), qw);
        return new PageUtils(page);

    }

    @Override
    public List<Long> selectSerarchAttrIds(List<Long> attrIds) {

       return baseMapper.selectSerarchAttrIds(attrIds);
    }


}